package com.xjc.agent;

import com.xjc.agent.core.util.LoaderUtil;
import java.net.URL;
import java.net.URLClassLoader;

/**
 * @author: 谢君臣
 * @Date: 2023/1/7-19:49
 * @version: 1.0
 * @function:
 */
public class AgentLoader extends URLClassLoader {

    public AgentLoader(URL[] urls, ClassLoader parent) {
        super(urls, parent);
    }

    public AgentLoader(String agentPath, String libPath, String confPath, ClassLoader rootClassLoader) {

        super(LoaderUtil.findJar(agentPath, libPath, confPath), rootClassLoader);
    }

    @Override
    protected synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
        System.out.println("name:" + name + ":开始尝试加载；");
        Class<?> aClass = findLoadedClass(name);
        if (aClass != null) {
            if (resolve) {
                resolveClass(aClass);
            }
            return aClass;
        }
        if ((name != null) && (name.startsWith("sun") || name.startsWith("java."))) {
            return super.loadClass(name, resolve);
        }
        try {
            Class<?> klass = findClass(name);
            if (resolve) {
                resolveClass(klass);
            }
            return klass;
        } catch (ClassNotFoundException e) {
        }
        return super.loadClass(name, resolve);
    }
}
